package com.powerwyx.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powerwyx.apicommon.model.entity.InterfaceInfo;
import com.powerwyx.apicommon.model.entity.UserInterfaceInfo;
import com.powerwyx.project.common.ErrorCode;
import com.powerwyx.project.exception.BusinessException;
import com.powerwyx.project.mapper.UserInterfaceInfoMapper;
import com.powerwyx.project.model.vo.InterfaceInfoVO;
import com.powerwyx.project.service.InterfaceInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author 王艺锡
 * @version 1.0
 */
@Service
public class StatsServiceImpl implements StatsService {
    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private InterfaceInfoService interfaceInfoService;


    /**
     * 统计排名前三的接口总调用次数
     * @return
     */
    @Override
    public List<InterfaceInfoVO> listTopInvokeInterfaceInfo() {
        //查询排名前三的接口总调用次数
        List<UserInterfaceInfo> userInterfaceInfoList = userInterfaceInfoMapper.listTopInvokeInterfaceInfo(3);
        //查询每个接口的完整信息
        List<Long> interfaceInfoIdList = userInterfaceInfoList.stream().map(UserInterfaceInfo::getInterfaceInfoId).collect(Collectors.toList());
        List<InterfaceInfo> interfaceInfoList = interfaceInfoService.list(new QueryWrapper<InterfaceInfo>()
                .in("id", interfaceInfoIdList));

        if(CollectionUtil.isEmpty(interfaceInfoList)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        List<InterfaceInfoVO> interfaceInfoVOList = BeanUtil.copyToList(interfaceInfoList, InterfaceInfoVO.class);
        interfaceInfoVOList.forEach(each -> {
            Integer totalNum = userInterfaceInfoList.stream()
                    .filter(temp -> Objects.equals(each.getId(), temp.getInterfaceInfoId()))
                    .findFirst().get().getTotalNum();
            each.setTotalNum(totalNum);
        });

        return interfaceInfoVOList;
    }
}
